package controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import domin.Library;
import lombok.extern.slf4j.Slf4j;
import service.LibraryService;
import util.Condition;
import util.Pagination;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Collection;

@WebServlet("/library.ctl")
@Slf4j
public class LibraryController extends HttpServlet {
    private LibraryService libraryService;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("application/json;charset=UTF-8");
        try{
            this.responsesLibraries(response,null,null);
        }catch (SQLException e){
            System.out.println(e.getMessage());
        }
    }
    private void responsesLibraries(HttpServletResponse response, Collection<Condition> condition, Pagination pagination)
            throws ServletException, IOException,SQLException{

        Collection<Library> libraries = libraryService.getInstance().findAll(condition,pagination);

        String libraries_json = JSON.toJSONString(libraries, SerializerFeature.DisableCircularReferenceDetect);
        response.getWriter().println(libraries_json);
    }
}
